package com.whmskj.xjlhsc.controller;
import com.whmskj.xjlhsc.controller.vo.Result;
import com.whmskj.xjlhsc.mobie.Scheduling.entity.yg01EmployeeFiles;
import com.whmskj.xjlhsc.service.AttendanceNamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.whmskj.xjlhsc.service.dto.ConfirmQuery;
import com.whmskj.xjlhsc.utils.SCUtil;
import com.whmskj.xjlhsc.jitapi.dto.Emp;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 考勤点名相关接口
 * - 下拉筛选项（仅名称）
 * - 人员筛选（不需要传日期，自动取当天并判断早/晚班）
 */
@RestController
@RequestMapping("/api/attendance")
public class AttendanceNamingController {

    @Autowired
    private AttendanceNamingService attendanceNamingService;

    

    /**
     * 获取下拉筛选列表数据
     * 返回部门、工种、岗位、班组的完整列表数据
     * 对应表结构：
     * - 部门：xt01SectorManagement表 - nameOfDepartment字段
     * - 工种：managementOfXt03表 - nameOfJob字段
     * - 岗位：xt02JobManagement表 - nameOfPost字段
     * - 班组：groupTableYg02表 - className字段
     */
    @GetMapping("/filters")
    public Result getFilters() {
        Map<String, Object> data = new HashMap<>();
        data.put("departments", attendanceNamingService.listDepartmentNames());
        data.put("jobTypes", attendanceNamingService.listJobTypeNames());
        data.put("positions", attendanceNamingService.listPositionNames());
        data.put("groups", attendanceNamingService.listGroupNames());
        data.put("today", LocalDate.now().toString());
        data.put("shift", attendanceNamingService.detectCurrentShift());
        return Result.success(data);
    }

    /**
     * 人员筛选（部门/工种/岗位/班组），不需要日期，后端自动返回 today 与 shift。
     */
    @PostMapping("/employees/filter")
    public Result filterEmployees(@RequestBody Map<String, String> req) {
        String department = req.getOrDefault("department", null);
        String jobType = req.getOrDefault("jobType", null);
        String position = req.getOrDefault("position", null);
        String group = req.getOrDefault("group", null);

        List<yg01EmployeeFiles> list = attendanceNamingService.filterEmployees(department, jobType, position, group);

        Map<String, Object> data = new HashMap<>();
        data.put("today", LocalDate.now().toString());
        data.put("shift", attendanceNamingService.detectCurrentShift());
        data.put("employees", list);
        return Result.success(data);
    }

    /**
     * 考勤确认接口
     * 1. 登录校验 - 验证用户名和密码
     * 2. 权限验证 - 验证当前登录人是否为选中员工的考勤人（通过员工档案的classes字段判断）
     * 3. 数据插入 - 如果验证通过，将考勤确认数据插入到pro_personnel_stand_confirm表
     */
    @PostMapping("/confirmAttendance")
    public Result confirmAttendance(@RequestBody Map<String, Object> req) {
        try {
            // 获取请求参数
            String username = (String) req.get("username");
            String password = (String) req.get("password");
            @SuppressWarnings("unchecked")
            List<Integer> employeeIds = (List<Integer>) req.get("employeeIds");
            
            // 参数校验
            if (username == null || password == null || employeeIds == null || employeeIds.isEmpty()) {
                return Result.error("参数不完整");
            }
            
            // 1. 登录校验
            boolean loginSuccess = attendanceNamingService.validateLogin(username, password);
            if (!loginSuccess) {
                return Result.error("用户名或密码错误");
            }
            
            // 2. 获取当前登录人信息（登录人本身就是考勤人）
            String currentAttendant = attendanceNamingService.getCurrentAttendant(username);
            if (currentAttendant == null) {
                return Result.error("无法获取当前登录人信息");
            }
            
            // 3. 验证当前登录人是否为选中员工的考勤人（通过员工档案的classes字段判断）
            List<yg01EmployeeFiles> unauthorizedEmployees = attendanceNamingService
                .getUnauthorizedEmployees(employeeIds, currentAttendant);
            
            Map<String, Object> result = new HashMap<>();
            result.put("loginSuccess", true);
            result.put("currentAttendant", currentAttendant);
            result.put("unauthorizedEmployees", unauthorizedEmployees);
            result.put("unauthorizedCount", unauthorizedEmployees.size());
            
            if (!unauthorizedEmployees.isEmpty()) {
                result.put("message", "以下员工不是您的考勤人，无法进行考勤确认");
                return Result.success(result);
            } else {
                // 所有员工都是当前登录人的考勤人，执行考勤确认并插入数据
                boolean insertSuccess = attendanceNamingService.confirmAttendanceAndInsert(employeeIds, currentAttendant);
                if (insertSuccess) {
                    result.put("message", "考勤确认成功，数据已保存");
                    result.put("insertSuccess", true);
                } else {
                    result.put("message", "考勤确认失败，数据保存异常");
                    result.put("insertSuccess", false);
                }
                return Result.success(result);
            }
            
        } catch (Exception e) {
            return Result.error("考勤确认失败: " + e.getMessage());
        }
    }

    /**
     * 考勤记录分页筛选
     */
    @PostMapping("/records")
    public Result pageRecords(@RequestBody ConfirmQuery query){
        Page<Map<String, Object>> page = attendanceNamingService.pageRecords(query);
        return Result.success(page);
    }

    /**
     * 移动端：通过token获取“被当前登录人审核的员工列表”（员工档案classes=登录人姓名）
     */
    @GetMapping("/mobile/currentEmployee")
    public Result currentEmployeeByToken(){
        Emp loginEmp;
        try {
            loginEmp = SCUtil.getCurrentLoginEmp();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        // 直接返回被当前登录人(姓名)审核的员工
        java.util.List<yg01EmployeeFiles> audited = attendanceNamingService.listEmployeesAuditedByCurrent();
        return Result.success(audited);
    }
}
